package com.demo.common;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PdfExport {

    private static final float DEFAULT_FONT_SIZE = 12f;
    private static final float DEFAULT_LINE_HEIGHT = 20f;
    private static final float DEFAULT_MARGIN = 50f;

    public static void exportTextToPdf(String content, String outputPath) throws IOException {
        exportTextToPdf(content, outputPath, null, DEFAULT_FONT_SIZE);
    }

    public static void exportTextToPdf(String content, String outputPath,
                                       String fontPath, float fontSize) throws IOException {
        if (content == null || content.isEmpty()) {
            throw new IllegalArgumentException("导出内容不能为空");
        }

        // 确保输出目录存在
        File outputFile = new File(outputPath);
        if (outputFile.getParentFile() != null) {
            outputFile.getParentFile().mkdirs();
        }

        try (PDDocument document = new PDDocument()) {
            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);

            // 加载字体
            PDType0Font font = loadFont(document, fontPath);

            // 创建内容流
            PDPageContentStream contentStream = new PDPageContentStream(document, page);

            // 设置页面参数
            PDRectangle mediaBox = page.getMediaBox();
            float startX = DEFAULT_MARGIN;
            float startY = mediaBox.getHeight() - DEFAULT_MARGIN;
            float currentY = startY;

            // 分割文本行
            String[] lines = content.split("\n");

            try {
                // 开始文本写入
                contentStream.beginText();
                setFont(contentStream, font, fontSize);
                contentStream.newLineAtOffset(startX, startY);

                // 写入文本行
                for (String line : lines) {
                    // 检查是否需要换页
                    if (currentY < DEFAULT_MARGIN) {
                        // 结束当前页
                        contentStream.endText();
                        contentStream.close();

                        // 创建新页面
                        page = new PDPage(PDRectangle.A4);
                        document.addPage(page);
                        contentStream = new PDPageContentStream(document, page);

                        // 重置位置
                        currentY = mediaBox.getHeight() - DEFAULT_MARGIN;

                        // 开始新页的文本
                        contentStream.beginText();
                        setFont(contentStream, font, fontSize);
                        contentStream.newLineAtOffset(startX, currentY);
                    }

                    // 写入当前行
                    contentStream.showText(line);

                    // 移动到下一行
                    contentStream.newLineAtOffset(0, -DEFAULT_LINE_HEIGHT);
                    currentY -= DEFAULT_LINE_HEIGHT;
                }

                contentStream.endText();
            } finally {
                // 确保关闭内容流
                if (contentStream != null) {
                    contentStream.close();
                }
            }

            // 保存文档
            document.save(outputPath);
        }
    }

    private static PDType0Font loadFont(PDDocument document, String fontPath) throws IOException {
        if (fontPath != null) {
            Path fontPathObj = Paths.get(fontPath);
            if (Files.exists(fontPathObj)) {
                try {
                    return PDType0Font.load(document, fontPathObj.toFile());
                } catch (IOException e) {
                    System.err.println("警告：无法加载自定义字体: " + fontPath);
                }
            }
        }

        // 尝试加载系统字体
        String[] commonFonts = {
                "C:/Windows/Fonts/simhei.ttf",    // 黑体
                "C:/Windows/Fonts/simsun.ttc",    // 宋体
                "C:/Windows/Fonts/msyh.ttc",      // 微软雅黑
                "/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf", // Linux
                "/System/Library/Fonts/PingFang.ttc" // macOS
        };

        for (String f : commonFonts) {
            Path fontPathObj = Paths.get(f);
            if (Files.exists(fontPathObj)) {
                try {
                    PDType0Font font = PDType0Font.load(document, fontPathObj.toFile());
                    if (font != null) {
                        System.out.println("使用系统字体: " + f);
                        return font;
                    }
                } catch (IOException e) {
                    // 继续尝试下一个字体
                }
            }
        }

        return null; // 没有找到可用字体
    }

    private static void setFont(PDPageContentStream contentStream, PDType0Font font, float fontSize)
            throws IOException {
        if (font != null) {
            contentStream.setFont(font, fontSize);
        } else {
            // 使用兼容的字体设置
            contentStream.setFont(PDType1Font.HELVETICA, fontSize);
            System.err.println("警告：未找到中文字体，使用Helvetica（可能不支持中文）");
        }
    }
}
